package com.ggs.rg.ybjb.usermodule.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ggs.rg.ybjb.pojomodule.pojo.Mater;
import com.ggs.rg.ybjb.pojomodule.pojo.TGoodsOrder;
import com.ggs.rg.ybjb.pojomodule.pojo.TOrder;
import com.ggs.rg.ybjb.pojomodule.pojo.TUser;
import com.ggs.rg.ybjb.pojomodule.util.CommonUtil;
import com.ggs.rg.ybjb.pojomodule.util.StringTools;
import com.ggs.rg.ybjb.pojomodule.util.constants.ErrorEnum;
import com.ggs.rg.ybjb.usermodule.mapper.*;
import com.ggs.rg.ybjb.usermodule.service.TAddressService;
import com.ggs.rg.ybjb.usermodule.service.TOrderService;
import com.ggs.rg.ybjb.usermodule.util.OrderUtil;
import com.ggs.rg.ybjb.usermodule.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;


@Service
public class TOrderServiceImpl extends ServiceImpl<TOrderMapper, TOrder> implements TOrderService {

    @Autowired
    TOrderMapper tOrderMapper;

    @Autowired
    TGoodsOrderMapper tGoodsOrderMapper;

    @Autowired
    TCommentMapper tCommentMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    TAddressMapper tAddressMapper;

    @Autowired
    MaterMapper materMapper;

    @Autowired
    private RedisUtil redisUtil;            //自己写的操作redis的工具类,其实就是封装了redisTemplate的操作

    //根据手机号获取已付款订单
    @Override
    public JSONObject selectOrderByPhone(Integer pagesNumber,String phone,Integer status) {
        //创建分页对象
        Page<TOrder> page = new Page<>(pagesNumber,2);
        //设置分页不使用count()函数
        // page = page.setOptimizeCountSql(false).setSearchCount(false);
        //创建条件构造器
        QueryWrapper<TUser> wrapper = new QueryWrapper<TUser>();
        //向条件构造器加入条件
        wrapper.orderByDesc("create_time");
        //封装返回结果
        JSONObject resultJson = new JSONObject();

        List<Object> resultOrder = new ArrayList<>();
        if (status == 1){
            IPage<TOrder> orders = tOrderMapper.selectOrderByPhone(page,wrapper,phone);
            if (orders == null){
                System.out.println("手机号为:"+ phone +"的用户没有已付款订单");
                return null;
            }
            resultJson.put("pagesCount",orders.getPages());
            resultJson.put("pagesNumber",pagesNumber);
            for (TOrder order:orders.getRecords()){
                System.out.println("----------------------");
                System.out.println(order);
                System.out.println("----------------------");
                JSONObject result = OrderUtil.orderForJson(order,phone,tCommentMapper,tOrderMapper);
                resultOrder.add(result);
            }
        }else if (status == 0){
            IPage<TOrder> orders = tOrderMapper.selectUnpaidOrderByPhone(page,wrapper,phone);
            if (orders == null){
                System.out.println("手机号为:"+ phone +"的用户没有未付款订单");
                return null;
            }
            resultJson.put("pagesCount",orders.getPages());
            resultJson.put("pagesNumber",pagesNumber);
            for (TOrder order:orders.getRecords()){
                JSONObject result = OrderUtil.orderForJson(order,tOrderMapper);
                resultOrder.add(result);
            }
        }else{
            System.out.println("未知异常!!!");
            return null;
        }
        resultJson.put("orderList",resultOrder);
        return resultJson;
    }

    //根据oid获取订单详情
    @Override
    public JSONObject selectTOrderDetailById(String oid) {
       QueryWrapper<TOrder> queryWrapper = new QueryWrapper<>();
       queryWrapper.select("oid,price,create_time").eq("oid",oid).eq("status",0);
        TOrder tOrder = tOrderMapper.selectOne(queryWrapper);
        if (tOrder == null){
            System.out.println("oid为:" + oid + "的订单不存在!");
            return null;
        }
        JSONObject result = OrderUtil.orderForJson(tOrder,tOrderMapper);
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    //需要加锁!!!!
    public JSONObject pay(String oid, Integer aid) {
        // 首先查询订单是否存在,除非获取的信息有用到
        // 查询是否存在最好使用这样的语句
        // SELECT count(*) FROM `t_order` where oid=oid,性能高
        // 如下面的例子,order采用正常查询，因为查询出来的信息后面有用
        // address采用count(*)方式,因为没有需要用到的信息
        QueryWrapper<TOrder> queryOrder = new QueryWrapper<>();
        queryOrder.eq("status",0).eq("oid",oid);
        TOrder order = tOrderMapper.selectOne(queryOrder);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("aid",aid);
        Integer addressExists = tAddressMapper.selectCount(queryWrapper);
        if (StringTools.isNullOrEmpty(order) || addressExists == 0){
            System.out.println("没有该订单或该订单已付款或收货地址不存在");
            return CommonUtil.successJson("没有该订单或该订单已付款或收货地址不存在");
        }
        //查询库存是否足够
        QueryWrapper<TGoodsOrder> GQueryWrapper = new QueryWrapper<>();
        GQueryWrapper.eq("oid",oid);
        List<TGoodsOrder> tGoodsOrders = tGoodsOrderMapper.selectList(GQueryWrapper);
        for (TGoodsOrder goodsOrder:tGoodsOrders){
            //订单商品关系表中的pid
            Integer pid = goodsOrder.getPid();
            //订单商品关系表中的count,代表用户订单购买某商品的数量
            Integer count = goodsOrder.getCount();
            //根据关系表的pid查询商品,并获取库存,对比
            Mater mater = materMapper.selectById(pid);
            Integer materCount = mater.getCount();
            if (count > materCount){
                System.out.println("商品参数id为:"+pid+"的商品库存不足!");
                return CommonUtil.successJson("商品库存不足!");
            }
            UpdateWrapper<Mater> updateMater = new UpdateWrapper<>();
            updateMater.set("count",materCount-count).eq("pid",pid);
            int result = materMapper.update(null, updateMater);
            if (result < 1) {
                System.out.println("商品参数id为:"+pid+"的商品更新库存失败!");
                return CommonUtil.successJson("商品参数id为:"+pid+"的商品更新库存失败!");
            }
        }
        //获取用户余额,与订单价格相比，若是余额少于订单价,返回"余额不足"
        TUser user = userMapper.selectById(order.getPhone());
        if (user.getMoney()<order.getPrice()) {
            System.out.println("用户余额不足");
            return CommonUtil.successJson("用户余额不足");
        }
        //更新用户余额
        UpdateWrapper<TUser> updateUser = new UpdateWrapper();
        updateUser.set("money",user.getMoney()-order.getPrice()).eq("phone",user.getPhone());
        int userResult = userMapper.update(null, updateUser);
        //将redis缓存中的未付款订单标志删除,key格式为:"orderStatus."+tOrder.getOid()
        //手动删除,这样就不会执行"标志失效"的回调函数
        redisUtil.del("orderStatus." + oid);
        //把订单状态改为已付款，并加入收货地址
        UpdateWrapper<TOrder> updateOrder = new UpdateWrapper();
        updateOrder.set("aid",aid).set("status",1).eq("oid",oid);
        int orderResult = tOrderMapper.update(null, updateOrder);
        if (userResult == 1 && orderResult == 1)
            return CommonUtil.successJson();
        return CommonUtil.errorJson(ErrorEnum.E_100);
    }

    @Override
    public List<Long> selectTOrderByPhone(String phone) {
        return tOrderMapper.selectTOrderByPhone(phone);
    }

}
